const { spawn } = require('child_process');
const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
const path = require('path');

// 环境判断提升到模块作用域
const isProduction = (process.env.NODE_ENV || 'production') === 'production';

// 配置文件路径
const configPath = isProduction? path.join(__dirname, '../../electron/config.json'): path.join(__dirname, 'config.json');

// 读取配置
ipcMain.handle('read-config', async () => {
  try {
    const data = fs.readFileSync(configPath, 'utf8');
    const config = JSON.parse(data);
    config.storagePath = path.resolve(__dirname, config.storagePath);
    return config;
  } catch (err) {
    console.error('配置读取失败:', err);
  }
});

// 保存配置
ipcMain.handle('save-config', (event, config) => {
  try {
    const storagePath = path.resolve(__dirname, config.storagePath);

    if (!fs.existsSync(storagePath)) {
      fs.mkdirSync(storagePath, { recursive: true });
      console.log('目录创建成功:', storagePath);
    }

    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    return {
      success: true,
      message: '配置保存成功',
      storagePath: storagePath
    };
  } catch (err) {
    console.error('配置保存失败:', err);
    return {
      success: false,
      message: `保存失败: ${err.message}`,
      error: err.stack
    };
  }
});

const createWindow = () => {
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      webSecurity: false,
      preload: path.join(__dirname, 'preload.cjs'),
      userAgent: 'ElectronApp/1.0 Chrome/93.0.4577.82'
    },
    show: false
  });

  // 允许访问本地网络服务
  win.webContents.on('did-finish-load', () => {
    win.show();
    if (process.env.NODE_ENV === 'production') {
      win.webContents.executeJavaScript(`
        window.__ELECTRON_ENV__ = 'production';
        window.__API_BASE__ = 'http://' + window.location.hostname + ':3001';
      `);
    }
  });

  // 添加加载失败监听
  win.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    console.error('窗口加载失败:', {
      code: errorCode,
      description: errorDescription,
      url: win.webContents.getURL(),
      env: process.env.NODE_ENV
    });
  });

  win.webContents.on('dom-ready', () => {
    console.log('窗口DOM加载完成，当前URL:', win.webContents.getURL());
  });

  // 修改环境判断逻辑
  if (isProduction) {
    console.log('生产环境');
    win.loadFile(path.join(__dirname, '../dist/index.html'));
    // win.loadURL('http://localhost:3000');
  } else {
    console.log('开发模式');
    win.loadURL('http://localhost:3000');
  }
  // 打开开发工具
  // win.webContents.openDevTools();
  // const appUrl = isProduction
  //   ? `file://${path.join(process.resourcesPath, 'dist/index.html')}`
  //   : 'http://localhost:3000';

  // // 路径存在性检查
  // if (isProduction) {
  //   const indexPath = path.join(process.resourcesPath, 'dist/index.html');
  //   if (!fs.existsSync(indexPath)) {
  //     console.error('生产环境index.html不存在于:', indexPath);
  //     dialog.showErrorBox('启动错误', `未找到应用程序文件，请检查dist目录是否正常生成`);
  //     app.quit();
  //   }
  // }

  // win.loadURL(appUrl);
  // 打印最终资源路径
  console.log('应用资源路径:', {
    __dirname: __dirname,
    resourcesPath: process.resourcesPath,
    appPath: app.getAppPath()
  });
};

// 启动后端服务
const serverProcess = spawn(
  process.execPath,
  [
    '--unhandled-rejections=strict',
    isProduction 
      ? path.join(__dirname, '../server/index.cjs') // Cannot find module '/Applications/LanFileTransfer.app/Contents/Resources/app.asar/electron/server/index.cjs'
      : 'server/index.cjs'
  ],
  {
    stdio: 'pipe',
    env: {
      ...process.env,
      NODE_ENV: process.env.NODE_ENV || 'production',
      ELECTRON_RUN_AS_NODE: '1'
    }
  }
);

// 处理服务端输出
serverProcess.stdout.on('data', (data) => {
  console.log(`[SERVER] ${data}`);
});

serverProcess.stderr.on('data', (data) => {
  console.error(`[SERVER ERROR] ${data}`);
});

app.whenReady().then(() => {
  console.log('应用元数据:', {
    version: app.getVersion(),
    production: isProduction
  });
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 添加应用退出前的清理逻辑
app.on('before-quit', (event) => {
  console.log('开始清理进程...');
  event.preventDefault();
  
  // 终止后端服务进程
  if (serverProcess && !serverProcess.killed) {
    serverProcess.kill('SIGTERM');
    console.log('已终止后端服务进程');
  }
  
  // 强制退出应用
  setTimeout(() => {
    app.exit(0);
  }, 1000);
});

app.on('will-quit', (event) => {
  console.log('所有窗口已关闭，准备退出应用');
});

serverProcess.on('error', (err) => {
  console.error('服务启动失败:', err);
  app.quit();
});

serverProcess.on('exit', (code) => {
  if (code !== 0) {
    console.error(`服务异常退出，代码 ${code}`);
    app.quit();
  }
});

// 启动Electron应用
app.whenReady().then(() => {
  const { session } = require('electron');

  // 记录所有网络请求
  session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    // console.log('网络请求:', {
    //   url: details.url,
    //   method: details.method,
    //   timestamp: Date.now()
    // });
    callback({ requestHeaders: details.requestHeaders });
  });


}).catch(err => {
  console.error('应用启动失败:', err);
  app.quit();
});

// 退出时清理进程
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    serverProcess.kill();
    app.quit();
  }
});